<template>
  <div class="article-management">
    <AdminTable
      title="文章管理"
      :columns="columns"
      :data="articles"
      :pagination="pagination"
      @create="handleCreate"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="handleSearch"
      @change-page="handleChangePage"
    />
    
    <!-- 文章编辑/创建模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑文章' : '创建文章' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveArticle">
            <div class="form-group">
              <label>标题</label>
              <input type="text" v-model="currentArticle.title" required />
            </div>
            <div class="form-group">
              <label>作者</label>
              <input type="text" v-model="currentArticle.author" required />
            </div>
            <div class="form-group">
              <label>分类</label>
              <select v-model="currentArticle.category_id">
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>标签</label>
              <div class="tag-input">
                <input 
                  type="text" 
                  v-model="tagInput" 
                  @keyup.enter="addTag"
                  placeholder="输入标签后按回车添加"
                />
                <div class="tags-container">
                  <span 
                    v-for="(tag, index) in currentArticle.tags" 
                    :key="index" 
                    class="tag"
                  >
                    {{ tag }}
                    <button type="button" @click="removeTag(index)" class="remove-tag">×</button>
                  </span>
                </div>
              </div>
            </div>
            <div class="form-group">
              <label>摘要</label>
              <textarea v-model="currentArticle.summary" rows="3"></textarea>
            </div>
            <div class="form-group">
              <label>内容</label>
              <textarea v-model="currentArticle.content" rows="8" required></textarea>
            </div>
            <div class="form-group">
              <label>状态</label>
              <select v-model="currentArticle.status">
                <option :value="1">发布</option>
                <option :value="0">草稿</option>
              </select>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import AdminTable from '../components/AdminTable.vue'
import { articleAPI } from '../../../api/index.js'

export default {
  name: 'ArticleList',
  components: {
    AdminTable
  },
  setup() {
    const articles = ref([])
    const categories = ref([])
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    const showModal = ref(false)
    const isEditing = ref(false)
    const tagInput = ref('')
    const currentArticle = ref({
      id: null,
      title: '',
      author: '',
      category_id: '',
      tags: [],
      summary: '',
      content: '',
      status: 1
    })
    
    const columns = [
      { key: 'id', title: 'ID' },
      { key: 'title', title: '标题' },
      { key: 'author', title: '作者' },
      { key: 'category_name', title: '分类' },
      { key: 'view_count', title: '浏览量' },
      { key: 'like_count', title: '点赞数' },
      { key: 'create_time', title: '创建时间', type: 'date' },
      { key: 'status', title: '状态', type: 'status' }
    ]
    
    const fetchArticles = async (page = 1, search = '') => {
      try {
        const response = await articleAPI.getArticles({
          page: page,
          size: pagination.value.size,
          search: search
        })
        
        articles.value = response.data.articles
        pagination.value.total = response.data.total
        pagination.value.page = page
      } catch (error) {
        console.error('Failed to fetch articles:', error)
      }
    }
    
    const fetchCategories = async () => {
      try {
        const response = await articleAPI.getCategories()
        categories.value = response.data.categories || []
      } catch (error) {
        console.error('Failed to fetch categories:', error)
      }
    }
    
    const handleCreate = () => {
      isEditing.value = false
      currentArticle.value = {
        id: null,
        title: '',
        author: '',
        category_id: '',
        tags: [],
        summary: '',
        content: '',
        status: 1
      }
      tagInput.value = ''
      showModal.value = true
    }
    
    const handleEdit = (article) => {
      isEditing.value = true
      currentArticle.value = {
        ...article,
        tags: [...(article.tags || [])]
      }
      tagInput.value = ''
      showModal.value = true
    }
    
    const handleDelete = async (article) => {
      try {
        await articleAPI.deleteArticle(article.id)
        fetchArticles(pagination.value.page)
      } catch (error) {
        console.error('Failed to delete article:', error)
        alert('删除文章失败')
      }
    }
    
    const handleSearch = (query) => {
      fetchArticles(1, query)
    }
    
    const handleChangePage = (page) => {
      fetchArticles(page)
    }
    
    const addTag = () => {
      if (tagInput.value.trim() && !currentArticle.value.tags.includes(tagInput.value.trim())) {
        currentArticle.value.tags.push(tagInput.value.trim())
        tagInput.value = ''
      }
    }
    
    const removeTag = (index) => {
      currentArticle.value.tags.splice(index, 1)
    }
    
    const saveArticle = async () => {
      try {
        if (isEditing.value) {
          await articleAPI.updateArticle(currentArticle.value.id, currentArticle.value)
        } else {
          await articleAPI.createArticle(currentArticle.value)
        }
        closeModal()
        fetchArticles(pagination.value.page)
      } catch (error) {
        console.error('Failed to save article:', error)
        alert('保存文章失败')
      }
    }
    
    const closeModal = () => {
      showModal.value = false
    }
    
    onMounted(() => {
      fetchArticles()
      fetchCategories()
    })
    
    return {
      articles,
      categories,
      pagination,
      columns,
      showModal,
      isEditing,
      tagInput,
      currentArticle,
      handleCreate,
      handleEdit,
      handleDelete,
      handleSearch,
      handleChangePage,
      addTag,
      removeTag,
      saveArticle,
      closeModal
    }
  }
}
</script>

<style scoped>
.article-management {
  padding: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 100%;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #7f8c8d;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.tag-input {
  margin-top: 5px;
}

.tag-input input {
  margin-bottom: 10px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background: #3498db;
  color: white;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.remove-tag {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-weight: bold;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>